package com.jyt.peripheral.print

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.Intent
import android.util.Log
import com.google.gson.Gson
import com.jyt.peripheral.print.test.ActivityMain
import com.jyt.peripheral.runOnUiThread
import com.jyt.peripheral.toast
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * @author 陈聪
 * date 2021/4/7:14:02
 * 打印管理类
 */
open class PrintManager() {

    /**标签打印*/
    private var tagPrinter: BasePrinter? = null

    /**小票打印*/
    private var ticketPrinter: BasePrinter? = null

    companion object {
        val PRINT_TYPE_USB = 0 //外接usb标签打印
        val PRINT_TYPE_INER = 1 //内部自带一体小票打印
        private var instance: PrintManager? = null
        var mGson: Gson? = null
        var mContext: Context? = null

        /**
         * 获取单一打印实例
         */
        fun getInstance(context: Context? = null): PrintManager {
            synchronized(PrintManager::class) {
                if (instance == null) {
                    if(context!=null){
                        mContext = context
                    }
                    mGson = Gson()
                    instance = PrintManager()
                }
                return instance!!
            }
        }

        fun toast(msg: String) {
            mContext?.runOnUiThread { toast(msg) }
        }

        @SuppressLint("CheckResult")
        fun printCaches() {
            Observable.timer(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe {
                    when (printCache?.printType) {
                        PRINT_TYPE_USB -> instance?.toTagPrint(printCache, null)
                        PRINT_TYPE_INER -> instance?.toTicketPrint(printCache, null)
                    }
                }
        }

        var printCache: PrintInfo? = null
    }

    /**
     * 判断是否已完成初始化
     */
    fun initPrinter(type: Int): PrintManager {
        if (type == PRINT_TYPE_USB) {
            if (tagPrinter == null&&mContext!=null) {
                tagPrinter = USBprinter(mContext!!)
            }
        } else {
            if (ticketPrinter == null) {
                ticketPrinter = InerPrinter()
            } else {
                if (!ticketPrinter?.hadConnect()!!) {
                    ticketPrinter?.init()
                }
            }
        }
        return this
    }

    /**
     * 进行小票打印测试
     */
    fun testTicketPrinter(context: Context) {
        ticketPrinter?.close()//断开连接之后再进行调试
        context.startActivity(Intent(context, ActivityMain::class.java))
    }

    /**
     * 进行小票打印
     */
    fun toTicketPrint(info: PrintInfo?, callBack: ((Boolean) -> (Unit))?) {
        Thread {
            Log.e("toTicketPrint", info.toString())
            if (ticketPrinter != null && ticketPrinter?.hadConnect()!!) {
                if (info == null) {
                    toast("打印数据异常，PrintInfo is null")
                } else {
                    if((ticketPrinter as InerPrinter).isPrint){
                        toast("打印错误，请检查是否打印纸已用完!")
                        (ticketPrinter as InerPrinter).reSetprinter()
                        return@Thread
                    }
                    (ticketPrinter as InerPrinter).isPrint = true
                    if (ticketPrinter?.startPrint(info, callBack) == true) {
                        printCache = null
                    }
                    (ticketPrinter as InerPrinter).isPrint = false
                }
            } else {
                toast("正在连接打印机，请稍后!")
                info?.printType = PRINT_TYPE_INER
                printCache = info
                initPrinter(PRINT_TYPE_INER)
            }
        }.start()
    }

    /**
     * 打印测试
     */
    fun toTicketPrintTest( callBack: ((Boolean) -> (Unit))?) {
        if (ticketPrinter != null && ticketPrinter?.hadConnect()!!) {
            (ticketPrinter as? InerPrinter)?.testPrint(callBack)
        } else {
            mContext?.toast("正在连接打印机，请稍后!")
            initPrinter(PRINT_TYPE_INER)
        }
    }

    /**
     * 打开钱箱
     */
    fun openDrawer() {
        if (ticketPrinter != null && ticketPrinter?.hadConnect()!!) {
            (ticketPrinter as? InerPrinter)?.openDrawer()
        } else {
            mContext?.toast("此操作需连接打印机，请稍后!")
            initPrinter(PRINT_TYPE_INER)
        }
    }

    /**
     * 开始进行标签打印
     */
    fun toTagPrint(info: PrintInfo?, callBack: ((Boolean) -> (Unit))? = null) {
        if (tagPrinter != null) {
            if (info == null) {
                mContext?.toast("打印数据异常，PrintInfo is null")
            } else {
                tagPrinter?.startPrint(info, callBack)
                printCache = null
            }
        } else {
            info?.printType = PRINT_TYPE_USB
            printCache = info
            initPrinter(PRINT_TYPE_USB)
            mContext?.toast("正在连接USB打印机，请稍后!")
        }
    }

    fun usbPortSelect() {
        (tagPrinter as? USBprinter)?.usbPortSelect()
    }

    fun closeAll() {
        tagPrinter?.close()
        ticketPrinter?.close()
    }

}